<?php

namespace app\common\repository;

use app\common\model\SDKUsageLog;
use support\Container;

/**
 * SDK统计仓库类
 * 用于处理SDK使用统计相关数据操作
 */
class SDKStatsRepository
{
    /**
     * 获取使用统计
     */
    public function getUsageStats($appkey, $days = 30)
    {
        $startDate = date('Y-m-d', strtotime("-{$days} days"));
        $endDate = date('Y-m-d');
        
        return SDKUsageLog::where('appkey', $appkey)
            ->whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('DATE(created_at) as date, endpoint, status, COUNT(*) as count')
            ->groupBy('date', 'endpoint', 'status')
            ->orderBy('date', 'desc')
            ->get()
            ->toArray();
    }

    /**
     * 获取错误统计
     */
    public function getErrorStats($appkey, $days = 30)
    {
        $startDate = date('Y-m-d', strtotime("-{$days} days"));
        $endDate = date('Y-m-d');
        
        return SDKUsageLog::where('appkey', $appkey)
            ->where('status', 'error')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('DATE(created_at) as date, error_message, COUNT(*) as count')
            ->groupBy('date', 'error_message')
            ->orderBy('count', 'desc')
            ->get()
            ->toArray();
    }

    /**
     * 获取性能统计
     */
    public function getPerformanceStats($appkey, $days = 30)
    {
        $startDate = date('Y-m-d', strtotime("-{$days} days"));
        $endDate = date('Y-m-d');
        
        return SDKUsageLog::where('appkey', $appkey)
            ->where('status', 'success')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('DATE(created_at) as date, endpoint, 
                        AVG(response_time) as avg_response_time, 
                        MIN(response_time) as min_response_time, 
                        MAX(response_time) as max_response_time, 
                        COUNT(*) as count')
            ->groupBy('date', 'endpoint')
            ->orderBy('date', 'desc')
            ->get()
            ->toArray();
    }

    /**
     * 获取实时统计
     */
    public function getRealtimeStats($appkey, $hours = 24)
    {
        $startTime = date('Y-m-d H:i:s', strtotime("-{$hours} hours"));
        
        return SDKUsageLog::where('appkey', $appkey)
            ->where('created_at', '>=', $startTime)
            ->selectRaw('HOUR(created_at) as hour, endpoint, status, COUNT(*) as count')
            ->groupBy('hour', 'endpoint', 'status')
            ->orderBy('hour', 'desc')
            ->get()
            ->toArray();
    }

    /**
     * 获取平台分布统计
     */
    public function getPlatformStats($appkey, $days = 30)
    {
        $startDate = date('Y-m-d', strtotime("-{$days} days"));
        $endDate = date('Y-m-d');
        
        return SDKUsageLog::where('appkey', $appkey)
            ->whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('platform, COUNT(*) as count, AVG(response_time) as avg_response_time')
            ->groupBy('platform')
            ->orderBy('count', 'desc')
            ->get()
            ->toArray();
    }

    /**
     * 获取版本分布统计
     */
    public function getVersionStats($appkey, $days = 30)
    {
        $startDate = date('Y-m-d', strtotime("-{$days} days"));
        $endDate = date('Y-m-d');
        
        return SDKUsageLog::where('appkey', $appkey)
            ->whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('sdk_version, COUNT(*) as count, AVG(response_time) as avg_response_time')
            ->groupBy('sdk_version')
            ->orderBy('count', 'desc')
            ->get()
            ->toArray();
    }

    /**
     * 记录SDK使用日志
     */
    public function logUsage($appkey, $endpoint, $status, $responseTime = null, $errorMessage = null, $platform = null, $sdkVersion = null)
    {
        try {
            $log = new SDKUsageLog();
            $log->appkey = $appkey;
            $log->endpoint = $endpoint;
            $log->status = $status;
            $log->response_time = $responseTime;
            $log->error_message = $errorMessage;
            $log->platform = $platform;
            $log->sdk_version = $sdkVersion;
            $log->created_at = date('Y-m-d H:i:s');
            $log->save();
            
            return true;
        } catch (\Exception $e) {
            // 记录日志失败时不抛出异常，避免影响主流程
            error_log("SDK usage log failed: " . $e->getMessage());
            return false;
        }
    }
}